package com.lanmaoly.web.config;

import com.lanmaoly.web.common.exception.ArbitrationException;
import com.lanmaoly.web.server.dao.TbUserMapper;
import com.lanmaoly.web.server.entity.UserDetailsEntity;
import com.lanmaoly.web.server.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 查询MySQL用户数据
 *
 * @author Administrator
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TbUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("user details service username[{}]", username);
        TbUser tbUser = userMapper.selectByUsername(username);
        if (tbUser == null) {
            throw new ArbitrationException("为找到该用户");
        }
        if ("0".equals(tbUser.getStatus())) {
            throw new ArbitrationException("该用户冻结中");
        }
        UserDetailsEntity entity = new UserDetailsEntity(username, tbUser.getPassword(), AuthorityUtils.NO_AUTHORITIES);
        entity.setId(tbUser.getId());
        entity.setHeadPic(tbUser.getHeadPic());
        entity.setNickName(tbUser.getNickName());
//        return new User(username, tbUser.getPassword(), AuthorityUtils.NO_AUTHORITIES);
        return entity;
    }
}
